//
//  RemindDetailsViewController.m
//  EMMApp
//
//  Created by Mac on 16/5/11.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "RemindDetailsViewController.h"
#import "RemindDetailsCell.h"
#import "AddressPickView.h"
#import "GetRemindCategoryListApi.h"

@interface RemindDetailsViewController ()<UITableViewDelegate,UITableViewDataSource>

//定义tableView
@property (nonatomic, strong) UITableView *remindListTableView;

//数据源数组
@property (nonatomic, strong) NSMutableArray *dataArr;

//显示当前是否有记录
@property(nonatomic,strong)UILabel *label;

// 当前页码
@property (nonatomic, assign) int currentPageSize;

@end

@implementation RemindDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self creatNavigationController];
    _dataArr = [[NSMutableArray alloc] init];
    
    _remindListTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, EMM_HEIGHT-SafeAreaTopHeight) style:UITableViewStylePlain];
    _remindListTableView.delegate = self;
    _remindListTableView.dataSource = self;
    _remindListTableView.showsVerticalScrollIndicator = NO;
    _remindListTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_remindListTableView];
    self.remindListTableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewData];
    }];
    self.remindListTableView.mj_header.automaticallyChangeAlpha = YES;
    self.remindListTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backPushNotification:) name:@"isBackPushNotification" object:nil];
}

- (void)backPushNotification:(NSNotification *)notification {
    [self dismissViewControllerAnimated:NO completion:^{
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - 导航
- (void)creatNavigationController {
    [self updateNavBar];
    self.navigationItem.title = self.nameTitleString;

    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setFrame:CGRectMake(0, 0, 54 ,44)];
    [backBtn addTarget:self
                action:@selector(notBtnClick:)
      forControlEvents:UIControlEventTouchUpInside];
    [backBtn setBackgroundColor:[UIColor clearColor]];
    [backBtn setImage:[UIImage imageNamed:@"ico_back"] forState:UIControlStateNormal];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    if (EMM_WIDTH <= 320) {
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    }else if (EMM_WIDTH > 375){
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    }else{
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    }    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
}

#pragma mark - 导航左按钮响应事件
- (void)notBtnClick:(UIButton *)btn {
    if (_isNot == YES) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _dataArr = [[NSMutableArray alloc] init];
    [self.remindListTableView.mj_header beginRefreshing];
}

#pragma mark 下拉刷新数据
- (void)loadNewData {
    [_dataArr removeAllObjects];
    _currentPageSize = 1;
    [self postGetRemindListApiPageNumber:_currentPageSize];
    
}

#pragma mark 上拉加载更多数据
- (void)loadMoreData {
    _currentPageSize = _currentPageSize + 1;
    [self postGetRemindListApiPageNumber:_currentPageSize];
    
}

#pragma mark - 结束刷新
- (void)endRefreshing {
    [self.remindListTableView.mj_footer endRefreshing];
    [self.remindListTableView.mj_header endRefreshing];
}

#pragma mark - 提醒详情的Api
- (void)postGetRemindListApiPageNumber:(int)pageNumber {
    [self showHud:@"正加载请稍等...."];
    NSString *remindCategoryIdString;
    if (_isNot == YES) {
        remindCategoryIdString = self.remindCategoryId;
    }else {
        NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
        remindCategoryIdString = [userdf objectForKey:@"remindCategoryId"];
    }
    GetRemindCategoryListApi *api = [[GetRemindCategoryListApi alloc] initWithRemindCategoryId:remindCategoryIdString pageNumber:pageNumber pageSize:10 projectCode:_projectCode];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetRemindCategoryListApi *result = (GetRemindCategoryListApi *)request;
        if (result.isSuccess) {
            GetRemindCategoryList *get = result.resultData;
            for (RemindCategoryList *list in get.remindCategoryList) {
                [_dataArr addObject:list];
            }
            if (_dataArr.count == 0) {
                UILabel *jlLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, (EMM_HEIGHT-SafeAreaTopHeight-20)/2, EMM_WIDTH, 20)];
                jlLabel.text = @"当前没有记录";
                jlLabel.textAlignment = NSTextAlignmentCenter;
                jlLabel.font = [UIFont systemFontOfSize:15];
                [self.view addSubview:jlLabel];
            }
        } else {
            [self showToast:result.resultData.errorMsg];
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                [appInstance showLogin];
                
            } else if ( [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [self hideHud];
        [self endRefreshing];
        [_remindListTableView reloadData];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
        [self endRefreshing];
    }];
}

#pragma mark - UITableView 代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_dataArr.count > 0) {
        RemindCategoryList *cList = [_dataArr objectAtIndex:indexPath.row];
        return [self textHeightFromTextString:cList.remindContent width:[UIScreen mainScreen].bounds.size.width-115 fontSize:14]+40;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellId = @"RemindDetailsCellId";
    RemindDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"RemindDetailsCell" owner:self options:nil] lastObject];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_dataArr.count > 0) {
        RemindCategoryList *list = [_dataArr objectAtIndex:indexPath.row];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, [self textHeightFromTextString:list.remindContent width:[UIScreen mainScreen].bounds.size.width-115 fontSize:14]+40-0.5, EMM_WIDTH-20, 0.5)];
        imageView.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
        [cell addSubview:imageView];
        
        cell.itmerLabel.text = list.remindDate;
        cell.titleLabel.text = list.remindContent;
    }
    return cell;
}

#pragma mark - 动态计算行高
- (CGFloat)textHeightFromTextString:(NSString *)text width:(CGFloat)textWidth fontSize:(CGFloat)textSize {
    CGRect rect = [text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:textSize]} context:nil];
    //返回计算出的行高
    return ceilf(rect.size.height);
}

@end
